/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.unice.miage.oobdoo.entity.Album;
import com.unice.miage.oobdoo.entity.Commentaire;
import com.unice.miage.oobdoo.entity.Photo;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.manager.AlbumManager;
import com.unice.miage.oobdoo.manager.CommentaireManager;
import com.unice.miage.oobdoo.manager.PhotoManager;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Jeremy Romano
 */
public class PhotoServlet extends HttpServlet {

    @EJB
    private UtilisateurManager utilisateurManager;
    @EJB
    private AlbumManager albumManager;
    @EJB
    private PhotoManager photoManager;
    @EJB
    private CommentaireManager commentaireManager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String forwardTo = "";

        if (action != null) {
            if (action.equals("view")) {
                String idPhoto = request.getParameter("IdPhoto");

                if (!idPhoto.isEmpty()) {
                    Photo photo = photoManager.getPhotoById(Integer.valueOf(idPhoto));
                    if (photo != null) {
                        Utilisateur utilisateur = photo.getAlbum().getAuteur();
                        request.setAttribute("loginAuteur", utilisateur.getLogin());
                        request.setAttribute("idAuteur", utilisateur.getId());
                        request.setAttribute("album", photo.getAlbum().getNom());
                        request.setAttribute("idAlbum", photo.getAlbum().getId());
                        request.setAttribute("nomPhoto", photo.getNom());
                        request.setAttribute("idPhoto", photo.getId());
                        request.setAttribute("pathFileThumb", photo.getPathThumbPhoto());
                        request.setAttribute("pathFile", photo.getPathFile());
                        request.setAttribute("description", photo.getDescription());
                        request.setAttribute("commentaires", photo.getCommentairesList());
                        request.setAttribute("countCommentaires", photo.getCommentairesList().size());

                        // UPDATE DE LA NOTIFICATION
                        Collection<Commentaire> cs = photo.getCommentaires();
                        for (Commentaire c : cs) {
                            commentaireManager.updateViewCommentaire(c, true);
                            System.out.println("commentaire = " + c.getTexte());
                        }

                        forwardTo = "photo/photo.jsp?";
                    } else {
                        forwardTo = "photo/photo.jsp?ec=error";
                    }
                } else {
                    forwardTo = "photo/photo.jsp?ec=error";
                }
            } else if (action.equals("delete")) {
                String idPhoto = request.getParameter("IdPhoto");

                if (!idPhoto.isEmpty()) {
                    Photo p = photoManager.getPhotoById(Integer.valueOf(idPhoto));
                    Album a = p.getAlbum();

                    Object[] commentaires = p.getCommentaires().toArray();
                    for (int j = 0; j < commentaires.length; j++) {

                        Commentaire c = (Commentaire) commentaires[j];
                        Utilisateur auteur = c.getAuteur();

                        photoManager.deleteCommentaire(p, c);
                        utilisateurManager.deleteCommentaire(auteur, c);
                        commentaireManager.deleteCommentaire(c);
                    }
                    albumManager.deletePhoto(a, p);
                    photoManager.deletePhoto(p);
                    removeFilePhoto(p);
                    forwardTo = "AlbumServlet?action=view&IdAlbum=" + p.getAlbum().getId();
                }
            }
        }
        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
        dp.forward(request, response);
    }
    
    private void removeFilePhoto(Photo p) {
        try {
            String path = this.getServletContext().getInitParameter("PATH") + "upload/" + p.getAlbum().getAuteur().getId() + "/" + p.getAlbum().getId() + "/";

            File file = new File(path + p.getPathFile());
            File thumbH = new File(path + p.getPathThumbHome());
            File thumbL = new File(path + p.getPathThumbList());
            File thumbP = new File(path + p.getPathThumbPhoto());

            Files.delete(file.toPath());
            Files.delete(thumbH.toPath());
            Files.delete(thumbL.toPath());
            Files.delete(thumbP.toPath());
        } catch (IOException ex) {
            Logger.getLogger(AlbumServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
